package com.codestudy.controller;

import com.codestudy.common.AliOSSUtils;
import com.codestudy.entity.Result1;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

//添加文件--阿里云oss
@Api(tags = "添加文件接口")
@RestController
@Slf4j
@CrossOrigin  //运行跨域
@RequestMapping("/upload")
public class UploadController {

    @Autowired //把oss工具类注入进来
    private AliOSSUtils aliOSSUtils;

    @ApiOperation(value = "上传文件")
    @PostMapping("/add")
    public Result1 upload(MultipartFile file) throws IOException {  //抛异常
        log.info("文件上传,文件名：{}", file.getOriginalFilename());

        //调用阿里云oss工具类进行文件上传
        String url = aliOSSUtils.upload(file);
        log.info("文件url为：{}", url);
        return Result1.success(url);
    }

    @ApiOperation(value = "删除文件")
    @PostMapping("/del")
    public Result1 upload(String filename) throws IOException {  //抛异常
        int i = filename.lastIndexOf('/'); //获取最后一个斜杠的索引
        String file = filename.substring(i + 1);
        log.info("要删除的文件名：{}", file);
        return aliOSSUtils.del(file);
    }

}
